package com.heima.schedule.interceptor;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.threadUtil.ThreadLocalUtil;
import com.heima.utils.common.threadUtil.UserInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class AppTokenInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求头
        String userId = request.getHeader("userId");
        //存入线程
        if(StringUtils.isNotEmpty(userId)&&!StringUtils.equals(userId,"0")){
            UserInfo userInfo = new UserInfo();
            userInfo.setId(Integer.valueOf(userId));
            ThreadLocalUtil.set(userInfo);
            return super.preHandle(request, response, handler);
        }
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.getWriter().write(JSON.toJSONString(ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH)));
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ThreadLocalUtil.remove();
        super.postHandle(request, response, handler, modelAndView);
    }
}
